﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using HowtoScene.OpenGL;
namespace HowtoScene.OpenGLUT
{
  public partial class CH03 : OpenGLControl
  {
    public CH03()
    {
      InitializeComponent();
    }
    protected override void OnCreateControl()
    {
      GL.glClearDepth(1.0);
      GL.glDepthFunc(GL.GL_LEQUAL);
      GL.glEnable(GL.GL_DEPTH_TEST);
      GL.glShadeModel(GL.GL_SMOOTH);
      GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);
    }
    public override void glDraw()
    {
      GL.glClearColor(0, 0, 0, 1);
      GL.glColor3f(0, 1, 0);
      GL.glClear(Win32GL.GL_COLOR_BUFFER_BIT);
      //绕X轴旋转90度,要不然,这个结果看起来就像是一个圆,因为OpenGL的Z轴,默认是和屏幕垂直的,
      //这样下面的点阵绕Z轴上升的过程在投影到屏幕上后,Z轴的效果实际上消失了.绕X轴旋转90度,可以
      //让Z轴成为平行于屏幕的方向.
      GL.glRotated(90, 1, 0, 0);
      //绕Y轴旋转30度,为了让结果看起来更酷一点.绕Y轴旋转后,X,Z轴在平面上就不再是横平竖直的了,而是
      //倾斜的,所以可以看到随着X的变化,点也会升高.
      GL.glRotated(30, 0, 1, 0);
      GL.glBegin(Win32GL.GL_POINTS);
      //绘制一个螺旋向上的点阵
      double z = -50;
      for (double angle = 0; angle <= 6 * Math.PI; angle += 0.1)
      {
        double x = 50* Math.Sin(angle);
        double y = 50 * Math.Cos(angle);
        GL.glVertex3d(x, y, z);
        z += 0.5;
      }
      GL.glEnd();    
    }
    protected override void OnSizeChanged(EventArgs e)
    {      
      base.OnSizeChanged(e);
      float range = 100.0f;
      int width = this.Size.Width;
      int height = this.Size.Height;
      //设置视口
      GL.glViewport(0, 0, width, height);
      //下面开始设置投影矩阵
      GL.glMatrixMode(Win32GL.GL_PROJECTION);
      GL.glLoadIdentity();   
      //保证x/y比例和控件的宽高比例一致,避免变形.
      if (width < height)
      {
        GL.glOrtho(-range, range, -range * height / width,
          range * height / width, -range, range);
      }
      else
      {
        GL.glOrtho(-range * width / height, range * width / height,
          -range, range, -range, range);
      }
      //设置模型视图矩阵
      GL.glMatrixMode(Win32GL.GL_MODELVIEW);
      GL.glLoadIdentity();
    }
  }
}
